package com.bee.剑指offer;

import java.util.ArrayList;

/**
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2021-04-18
 */
public class 顺时针打印矩阵 {

    public static ArrayList<Integer> print(int lx, int ly, int rx, int ry, int[][] matrix, ArrayList<Integer> result) {
        for (int i = ly; i <= ry; i++) {
            result.add(matrix[lx][i]);
        }
        for (int j = lx + 1; j <= rx; j++) {
            result.add(matrix[j][ry]);
        }
        int w = ry - ly;
        int h = rx - lx;
        //  难点，在遍历一行的时候，由于上面已经遍历了一遍，所以这里高度，函数必须>0才你遍历，否则会有重复数据
        if (h > 0) {
            for (int i = ry - 1; i >= ly; i--) {
                result.add(matrix[rx][i]);
            }
        }
        // 在遍历一列的时候必须控制行数大于0，ry-ly > 0，只有一列，上面已经遍历了这一列，ry-ly > 0
        if (w > 0) {
            for (int j = rx - 1; j >= lx + 1; j--) {
                result.add(matrix[j][ly]);
            }
        }
        return result;
    }

    public static ArrayList<Integer> printMatrix(int[][] matrix) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        if (matrix == null || matrix.length <= 0) {
            return result;
        }
        int ly = 0;
        int lx = 0;
        int rx = matrix.length - 1;
        int ry = matrix[0].length - 1;
        while (lx <= rx && ly <= ry) {
            print(lx, ly, rx, ry, matrix, result);
            lx++;
            ly++;
            rx--;
            ry--;
        }
        return result;
    }

    public static void main(String[] args) {
        int[][] matrix = new int[5][1];
        int count = 1;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                matrix[i][j] = count;
                count++;
            }
        }
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.println(matrix[i][j]);
            }
        }
        ArrayList<Integer> integers = printMatrix(matrix);
        System.out.println(integers.toString());
    }
}
